<script setup>
import { ref, onMounted, watch } from 'vue';
import { orderStatisticsService, userStatisticsService } from '@/src-manager/api/operation.js';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

const OrderStartTime = ref('');
const OrderEndTime = ref('');
const UserStartTime = ref('');
const UserEndTime = ref('');

const rangeTime = ref({
    startTime: '',
    endTime: ''
});

const formatDateTime = (date) => {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const orderData = ref({
    totalCompletedOrders: 0,
    totalCompletedTickets: 0,
    totalEarnedAmount: 0.0,
    totalFlightSchedules: 0
});

const userData = ref({
    newAddUsersInRangeTime: 0,
    totalUsers: 0,
    newAddMembersInRangeTime: 0,
    totalMembers: 0
});

const formatDate = (date) => {
    return date/10000;
}

const getOrderData = async () => {
    if (OrderStartTime.value && OrderEndTime.value) {
        rangeTime.value.startTime = formatDateTime(OrderStartTime.value);
        rangeTime.value.endTime = formatDateTime(OrderEndTime.value);

        try {
            const result = await orderStatisticsService(rangeTime.value);
            if (result.code === 200) {
                orderData.value = result.data;
            } else {
                ElMessage.error(result.msg);
            }
        } catch (error) {
            ElMessage.error("获取订单统计数据失败: " + error.message);
        }
    }
};

const getUserData = async () => {
    if (UserStartTime.value && UserEndTime.value) {
        rangeTime.value.startTime = formatDateTime(UserStartTime.value);
        rangeTime.value.endTime = formatDateTime(UserEndTime.value);

        try {
            const result = await userStatisticsService(rangeTime.value);
            if (result.code === 200) {
                userData.value = result.data;
            } else {
                ElMessage.error(result.msg);
            }
        } catch (error) {
            ElMessage.error("获取用户统计数据失败: " + error.message);
        }
    }
}

const optionOrderBar = ref({});
const renderOrderBarOptions = () => {
    return {
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' }
        },
        xAxis: {
            type: 'category',
            data: ['完成订单总数/个', '完成票务总数/个', '交易总额/万元', '班次总数/趟'],
            axisLabel: {
                textStyle: {
                    color: '#333',
                    fontSize: 11
                }
            }
        },
        yAxis: { 
            type: 'value',
            axisLabel: {
                textStyle: {
                    color: '#333',
                    fontSize: 14
                }
            }
        },
        series: [
            {
                name: '订单及班次分析',
                type: 'bar',
                data: [
                    orderData.value.totalCompletedOrders,
                    orderData.value.totalCompletedTickets,
                    formatDate(orderData.value.totalEarnedAmount).toFixed(2),
                    orderData.value.totalFlightSchedules
                ],
                emphasis: { focus: 'series' },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#188df0' },
                        { offset: 1, color: '#188df0' }
                    ])
                }
            }
        ]
    };
};

const optionUserBar = ref({});
const renderUserBarOptions = () => {
    return {
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' }
        },
        xAxis: {
            type: 'category',
            data: ['用户总数', '新增用户', '会员总数', '新增会员'],
            axisLabel: {
                textStyle: {
                    color: '#333',
                    fontSize: 11
                }
            }
        },
        yAxis: { 
            type: 'value',
            axisLabel: {
                textStyle: {
                    color: '#333',
                    fontSize: 14
                }
            }
        },
        series: [
            {
                name: '用户及会员分析',
                type: 'bar',
                data: [
                    userData.value.totalUsers,
                    userData.value.newAddUsersInRangeTime,
                    userData.value.totalMembers,
                    userData.value.newAddMembersInRangeTime,
                ],
                emphasis: { focus: 'series' },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#ff7c7c' },
                        { offset: 0.5, color: '#ff4d4d' },
                        { offset: 1, color: '#ff1a1a' }
                    ])
                }
            }
        ]
    };
};

watch(orderData, () => {
    optionOrderBar.value = renderOrderBarOptions();
    if (orderChart.value) {
        orderChart.value.setOption(optionOrderBar.value);
    }
});

watch(userData, () => {
    optionUserBar.value = renderUserBarOptions();
    if (userChart.value) {
        userChart.value.setOption(optionUserBar.value);
    }
});

onMounted(() => {
    optionOrderBar.value = renderOrderBarOptions();
    optionUserBar.value = renderUserBarOptions();
});

const orderChart = ref(null);
const userChart = ref(null);

const isOrderDataValid = ref(false);
const isUserDataValid = ref(false);

watch([OrderStartTime, OrderEndTime], () => {
    isOrderDataValid.value = OrderStartTime.value && OrderEndTime.value && new Date(OrderEndTime.value) > new Date(OrderStartTime.value);
});

watch([UserStartTime, UserEndTime], () => {
    isUserDataValid.value = UserStartTime.value && UserEndTime.value && new Date(UserEndTime.value) > new Date(UserStartTime.value);
});
</script>

<template>
    <div class="container">
        <e-row>
            <div class="date-range-selector">
                <label for="start-dateTime">订单数据查询起始时间:</label>
                <el-date-picker v-model="OrderStartTime" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

                <label for="end-dateTime">订单数据查询结束时间:</label>
                <el-date-picker v-model="OrderEndTime" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

                <button @click="getOrderData()" :disabled="!isOrderDataValid" type="primary">Apply</button>
            </div>

            <div class="date-range-selector">
                <label for="user-start-dateTime">用户数据查询起始时间:</label>
                <el-date-picker v-model="UserStartTime" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                <label for="user-end-dateTime">用户数据查询结束时间:</label>
                <el-date-picker v-model="UserEndTime" type="datetime" placeholder="Pick a Date"
                    format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

                <button @click="getUserData()" :disabled="!isUserDataValid" type="primary">Apply</button>
            </div>
        </e-row>

        <div class="charts-container">
            <div class="chart">
                <v-chart ref="orderChart" :option="optionOrderBar"></v-chart>
            </div>
            <div class="chart">
                <v-chart ref="userChart" :option="optionUserBar"></v-chart>
            </div>
        </div>
    </div>
</template>

<style scoped>
:root {
    --primary-color: #007BFF;
    --secondary-color: #0056b3;
    --background-color: #f8f9fa;
    --text-color: #333;
}

.container {
    padding: 20px;
    background-color: var(--background-color);
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.date-range-selector {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    padding: 10px;
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.date-range-selector label {
    margin-right: 10px;
    color: var(--text-color);
    font-weight: 500;
}

.date-range-selector input {
    margin-right: 20px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
}

.apply-button {
    padding: 5px 10px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.apply-button:hover {
    background-color: var(--secondary-color);
}

.charts-container {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
}

.chart {
    width: 48%;
    height: 400px;
    background: white;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
</style>
